package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加用户
func CreateUser(c *gin.Context) {
	var user model.User
	_ = c.ShouldBindJSON(&user)
	// 查询用户是否存在
	code := model.CheckUser(user.Username)
	if code == errmsg.SUCCESS {
		model.CreateUser(&user)
	}
	if code == errmsg.ErrorUsernameUsed {
		code = errmsg.ErrorUsernameUsed
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"user":    user,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查询单个用户

// 查询用户列表
func GetUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))

	//if pageSize == 0 {
	//	// 通过 -1 消除 Limit 条件
	//	pageSize = -1
	//}
	//if pageNum == 0 {
	//	// 通过 -1 消除 Offset 条件
	//	pageNum = -1
	//}
	users := model.GetUsers(pageSize, pageNum)
	code := errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"users":   users,
		"message": errmsg.GetErrMsg(code),
	})
}

// 编辑用户
func EditUser(c *gin.Context) {
	var newUser model.User
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&newUser)
	// 查询用户是否存在
	code := model.CheckUser(newUser.Username)
	if code == errmsg.SUCCESS {
		model.EditUser(id, &newUser)
	}
	if code == errmsg.ErrorUsernameUsed {
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
